<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>【JDK源码笔记】- 请介绍下你了解的ThreadLocal，它的底层原理！ | 程序员小航</title><meta name="keywords" content="源码笔记,JDK"><meta name="author" content="liuzhihang"><meta name="copyright" content="liuzhihang"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="什么是红黑树？在HashMap中是怎么应用的？">
<meta property="og:type" content="article">
<meta property="og:title" content="【JDK源码笔记】- 请介绍下你了解的ThreadLocal，它的底层原理！">
<meta property="og:url" content="https://liuzhihang.com/2020/06/21/source-code-threadlocal.html">
<meta property="og:site_name" content="程序员小航">
<meta property="og:description" content="什么是红黑树？在HashMap中是怎么应用的？">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/threadlocal.jpeg">
<meta property="article:published_time" content="2020-06-21T02:00:00.000Z">
<meta property="article:modified_time" content="2020-12-27T09:23:14.595Z">
<meta property="article:author" content="liuzhihang">
<meta property="article:tag" content="源码笔记">
<meta property="article:tag" content="JDK">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/threadlocal.jpeg"><link rel="shortcut icon" href="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/favicon.ico"><link rel="canonical" href="https://liuzhihang.com/2020/06/21/source-code-threadlocal"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//www.google-analytics.com" crossorigin=""/><link rel="preconnect" href="//pingjs.qq.com"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google_site_verification" content="GZshAnnrC-4eCrl5h-e_5Rdk4lOUhRK7ShULoRi2q0E"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><script async="async" src="https://www.googletagmanager.com/gtag/js?id=UA-126394362-1"></script><script>window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-126394362-1');
</script><script>var _mtac = {};
(function() {
    var mta = document.createElement("script");
    mta.src = "//pingjs.qq.com/h5/stats.js?v2.0.4";
    mta.setAttribute("name", "MTAH5");
    mta.setAttribute("sid", "66540676");
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(mta, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: {"limitDay":730,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: undefined,
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '【JDK源码笔记】- 请介绍下你了解的ThreadLocal，它的底层原理！',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2020-12-27 17:23:14'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="//at.alicdn.com/t/font_1608878_xsf93f0c1a.css"><meta name="generator" content="Hexo 5.2.0"><link rel="alternate" href="/atom.xml" title="程序员小航" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/threadlocal.jpeg')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">程序员小航</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-layer-group"></i><span> 导航</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></li><li><a class="site-page child" href="/categories/"><i class="fa-fw fas fa-bookmark"></i><span> 分类</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 推荐</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/books/"><i class="fa-fw fas fa-book"></i><span> 书单</span></a></li><li><a class="site-page child" href="/movies/"><i class="fa-fw fas fa-film"></i><span> 电影</span></a></li><li><a class="site-page child" href="/games/"><i class="fa-fw fas fa-gamepad"></i><span> 游戏</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/contact/"><i class="fa-fw fas fa-comments"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-address-book"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-user-circle"></i><span> 关于</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 其他</span><i class="fas fa-chevron-down expand hide"></i></a><ul class="menus_item_child"><li><a class="site-page child" target="_blank" rel="noopener" href="https://juejin.im/user/1987506650493117"><i class="fa-fw iconfont iconjuejin-1"></i><span> 掘金</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.zhihu.com/people/liuzhihang"><i class="fa-fw iconfont iconzhihu1"></i><span> 知乎</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://www.infoq.cn/profile/00B8AE08DA916E/publish"><i class="fa-fw iconfont iconweibiaoti-1"></i><span> InfoQ</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://blog.csdn.net/qq_36535538"><i class="fa-fw iconfont iconcsdn"></i><span> CSDN</span></a></li><li><a class="site-page child" target="_blank" rel="noopener" href="https://leetcode-cn.com/u/liuzhihang/"><i class="fa-fw iconfont iconleetcode"></i><span> LeetCode</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">【JDK源码笔记】- 请介绍下你了解的ThreadLocal，它的底层原理！</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-06-21T02:00:00.000Z" title="发表于 2020-06-21 10:00:00">2020-06-21</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2020-12-27T09:23:14.595Z" title="更新于 2020-12-27 17:23:14">2020-12-27</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/JDK/">JDK</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">3.8k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>15分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="【JDK源码笔记】- 请介绍下你了解的ThreadLocal，它的底层原理！"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/2020/06/21/source-code-threadlocal.html#post-comment"><span class="gitalk-comment-count"></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><blockquote>
<p><strong>前言</strong></p>
<p>业务开发中经常使用 ThreadLocal 来存储用户信息等线程私有对象… ThreadLocal 内部构造是什么样子的？为什么可以线程私有？常说的内存泄露又是怎么回事？</p>
<p>公众号：liuzhihangs ，记录工作学习中的技术、开发及源码笔记；时不时分享一些生活中的见闻感悟。欢迎大佬来指导！</p>
</blockquote>
<h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><blockquote>
<p>ThreadLocal 类提供了线程局部变量。和正常对象不同的是，每个线程都可以访问 get()、set() 方法，获取独属于自己的副本。 ThreadLocal 实例通常是类中的私有静态字段，并且其状态和线程关联。<br>每个线程都保持对其线程局部变量副本的隐式引用，只要线程是活动的并且 ThreadLocal 实例访问; 一个线程消失之后，所有的线程局部实例的副本都会被垃圾回收（除非存在对这些副本的其他引用）。</p>
</blockquote>
<h3 id="使用"><a href="#使用" class="headerlink" title="使用"></a>使用</h3><p>有这么一种使用场景，收到 web 请求，先进行 token 验证，而这个 token，可以解析出用户 user 的信息。所以我这边一般是这样使用的：</p>
<ol>
<li>自定义注解， <code>@CheckToken</code> ， 标识该方法需要校验 token。</li>
<li>在 <code>Interceptor</code>（拦截器）中检查，如果方法有 <code>@CheckToken</code> 注解则校验 token。</li>
<li>从Header中获取 <code>Authorization</code> ，请求第三方或者自己的逻辑校验 token ，并解析成 user。</li>
<li>将user放到<code>ThreadLocal</code>中。</li>
<li>controller、service 在后续使用中， 如果需要 user 信息，可以直接从 <code>ThreadLocal</code> 中获取。</li>
<li>使用结束后进行remove。</li>
</ol>
<h4 id="代码如下："><a href="#代码如下：" class="headerlink" title="代码如下："></a>代码如下：</h4><pre><code class="java">
public class LocalUserUtils &#123;

    /**
     * 用户信息保存至 ThreadLocal 中
     */
    private static final ThreadLocal&lt;User&gt; USER_THREAD_LOCAL = new ThreadLocal&lt;&gt;();

    public static void set(User user) &#123;
        USER_THREAD_LOCAL.set(user);
    &#125;

    public static User get() &#123;
        return USER_THREAD_LOCAL.get();
    &#125;

    public static void remove() &#123;
        USER_THREAD_LOCAL.remove();
    &#125;

&#125;

/**
 * 1. 加上注解 CheckToken
 * 只有方法， 类忽略
 */
@CheckToken
@PostMapping(&quot;/doXxx&quot;)
public Result&lt;Resp&gt; doXxx(@RequestBody Req req) &#123;

    Resp resp = xxxService.doXxx(req);

    return result.success(resp);
&#125;

/**
 * 2. 3. 4.
 */
@Component
public class TokenInterceptor implements HandlerInterceptor &#123;

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception &#123;
        LocalUserUtils.remove();
    &#125;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception &#123;
        // 请求方法是否存在注解
        boolean assignableFrom = handler.getClass().isAssignableFrom(HandlerMethod.class);

        if (!assignableFrom) &#123;
            return true;
        &#125;

        CheckToken checkToken = null;
        if (handler instanceof HandlerMethod) &#123;
            checkToken = ((HandlerMethod) handler).getMethodAnnotation(CheckToken.class);
        &#125;

        // 没有加注解 直接放过
        if (checkToken == null) &#123;
            return true;
        &#125;

        // 从Header中获取Authorization
        String authorization = request.getHeader(&quot;Authorization&quot;);
        log.info(&quot;header authorization : &#123;&#125;&quot;, authorization);
        if (StringUtils.isBlank(authorization)) &#123;
            log.error(&quot;从Header中获取Authorization失败&quot;);
            throw CustomExceptionEnum.NOT_HAVE_TOKEN.throwCustomException();
        &#125;

        User user = xxxUserService.checkAuthorization(authorization);
        // 放到
        LocalUserUtils.set(user);

        return true;
    &#125;
&#125;

/**
 * 5. 使用
 * 只有方法， 类忽略
 */
@Override
public Resp doXxx(Req req) &#123;

    User user = LocalUserUtils.get();

    // do something ...

    return resp;
&#125;</code></pre>
<img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/640.jpeg"  div align=center />

<h4 id="抛出问题"><a href="#抛出问题" class="headerlink" title="抛出问题"></a>抛出问题</h4><ol>
<li>为什么可以线程私有？</li>
<li>为什么建议声明为静态？</li>
<li>为什么强制使用后必须remove？</li>
</ol>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/19.png" alt="19"></p>
<p>图 | 阿里巴巴 - Java开发手册（截图）</p>
<p><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/6.png" alt="6"></p>
<p>图 | 阿里巴巴 - Java开发手册（截图）</p>
<h3 id="源码分析"><a href="#源码分析" class="headerlink" title="源码分析"></a>源码分析</h3><h4 id="Thread"><a href="#Thread" class="headerlink" title="Thread"></a>Thread</h4><pre><code class="java">
public class Thread implements Runnable &#123;
    // 省略 ...

    ThreadLocal.ThreadLocalMap threadLocals = null;

    ThreadLocal.ThreadLocalMap inheritableThreadLocals = null;

    // 省略 ...
&#125;</code></pre>
<p>可以看出 <code>Thread</code> 对象中声明了 <code>ThreadLocal.ThreadLocalMap</code> 对象，每个线程都有自己的工作内存，每个线程都有自己的 <code>ThreadLocal. ThreadLocalMap</code> 对象，所以在线程之间是互相<code>隔离</code>的。</p>
<h4 id="ThreadLocal"><a href="#ThreadLocal" class="headerlink" title="ThreadLocal"></a>ThreadLocal</h4><p>ThreadLocal则是一个泛型类，同时提供 <code>set()</code>、<code>get()</code>、<code>remove()</code> 等<code>静态</code>方法。</p>
<pre><code class="java">public class ThreadLocal&lt;T&gt; &#123;

    // 线程本地hashCode
    private final int threadLocalHashCode = nextHashCode();

    // 获取此线程局部变量的当前线程副本中的值
    public T get() &#123;...&#125;
    // 设置当前线程的此线程局部变量的复制到指定的值
    public void set(T value) &#123;...&#125;
    // 删除当前线程的此线程局部变量的值
    public void remove() &#123;...&#125;
    // ThreadLocalMap只是用来维持线程本地值的定制Map
    static class ThreadLocalMap &#123;...&#125;
&#125;</code></pre>
<h5 id="set-T-value-方法"><a href="#set-T-value-方法" class="headerlink" title="set(T value)方法"></a>set(T value)方法</h5><pre><code class="java">
public void set(T value) &#123;
    // 获取当前线程
    Thread t = Thread.currentThread();
    // 获取当前线程的 threadLocals 属性
    ThreadLocalMap map = getMap(t);
    if (map != null)
        // 存在则赋值
        map.set(this, value);
    else
        // 不存在则直接创建
        createMap(t, value);
&#125;
// 根据线程获取当前线程的ThreadLocalMap
ThreadLocalMap getMap(Thread t) &#123;
    return t.threadLocals;
&#125;
// 创建ThreadLocalMap 并赋值给当前线程的threadLocals字段
void createMap(Thread t, T firstValue) &#123;
    t.threadLocals = new ThreadLocalMap(this, firstValue);
&#125;</code></pre>
<p>1.<code>Thread.currentThread()</code> 先获取到当前线程。<br>2. 获取当前线程的 <code>threadLocals</code> 属性，即 <code>ThreadLocalMap</code>。<br>3. 判断 Map 是否存在，存在则赋值，不存在则创建对象。</p>
<h5 id="get-方法"><a href="#get-方法" class="headerlink" title="get()方法"></a>get()方法</h5><pre><code class="java">
public T get() &#123;
    // 获取当前线程
    Thread t = Thread.currentThread();
    // 获取当前线程的 threadLocals 属性
    ThreadLocalMap map = getMap(t);
    // map不为空
    if (map != null) &#123;
        // 根据当前ThreadLocal获取的ThreadLocalMap的Entry节点
        ThreadLocalMap.Entry e = map.getEntry(this);
        if (e != null) &#123;
            // 获取节点的value 并返回
            @SuppressWarnings(&quot;unchecked&quot;)
            T result = (T)e.value;
            return result;
        &#125;
    &#125;
    // 设置初始值并返回 （null）
    return setInitialValue();
&#125;
</code></pre>
<p>1.<code>Thread.currentThread()</code> 先获取到当前线程。<br>2. 获取当前线程的 <code>threadLocals</code> 属性，即 <code>ThreadLocalMap</code> 。<br>3. 判断 Map 不为空，根据当前 <code>ThreadLocal</code> 对象获取 <code>ThreadLocalMap.Entry</code> 节点, 从节点中获取 value。<br>4.<code>ThreadLocalMap</code> 为空或者 <code>ThreadLocalMap.Entry</code> 为空，则初始化 ThreadLocalMap 并返回。</p>
<h5 id="remove-方法"><a href="#remove-方法" class="headerlink" title="remove()方法"></a>remove()方法</h5><pre><code class="java">public void remove() &#123;
    // 获取当前线程的ThreadLocalMap
    ThreadLocalMap m = getMap(Thread.currentThread());
    // 不为空， 从ThreadLocalMap中移除该属性
    if (m != null)
        m.remove(this);
&#125;</code></pre>
<p>阅读 <code>set()</code>、<code>get()</code>、<code>remove()</code> 的源码之后发现后面其实是操作的 <code>ThreadLocalMap</code>, 主要还是操作的 <code>ThreadLocalMap</code> 的 <code>set()</code>、<code>getEntry()</code>、<code>remove()</code> 以及构造函数。下面看是看 ThreadLocalMap 的源码。</p>
<h4 id="ThreadLocalMap"><a href="#ThreadLocalMap" class="headerlink" title="ThreadLocalMap"></a>ThreadLocalMap</h4><pre><code class="java">static class ThreadLocalMap &#123;

    /**
     * Entry节点继承WeakReference是弱引用
     */
    static class Entry extends WeakReference&lt;ThreadLocal&lt;?&gt;&gt; &#123;
        /** 与此ThreadLocal关联的值。 */
        Object value;

        Entry(ThreadLocal&lt;?&gt; k, Object v) &#123;
            super(k);
            value = v;
        &#125;
    &#125;
    // 初始容量-必须是2的幂
    private static final int INITIAL_CAPACITY = 16;

    // 表，根据需要调整大小. table.length必须始终为2的幂.
    private ThreadLocal.ThreadLocalMap.Entry[] table;

    // 表中的条目数。 
    private int size = 0;

    // 扩容阈值  
    private int threshold; // Default to 0
    // 设置阀值为长度的 2/3   
    private void setThreshold(int len) &#123;
        threshold = len * 2 / 3;
    &#125;
    // 构造函数
    ThreadLocalMap(ThreadLocal&lt;?&gt; firstKey, Object firstValue) &#123;...&#125;

    // 根据ThreadLocal获取节点Entry
    private ThreadLocal.ThreadLocalMap.Entry getEntry(ThreadLocal&lt;?&gt; key) &#123;...&#125;

    // set ThreadLocalMap的k-v
    private void set(ThreadLocal&lt;?&gt; key, Object value) &#123;...&#125;

    // 移除当前值
    private void remove(ThreadLocal&lt;?&gt; key) &#123;...&#125;
&#125;
</code></pre>
<ol>
<li>Entry 继承了 <code>WeakReference&lt;ThreadLocal&lt;?&gt;</code> 也就意味着， <code>Entry 节点的 key 是弱引用</code>。</li>
<li>Entry 对象的key弱引用，指向的是 <code>ThreadLocal</code> 对象。</li>
<li>线程对象执行完毕，线程对象内实例属性会被回收，此时线程内 <code>ThreadLocal</code> 对象的<code>引用</code>被置为 <code>null</code> ，即 Entry 的 <code>key</code> 为 <code>null</code>, key 会被垃圾回收。</li>
<li>ThreadLocal 对象通常为私有静态变量， 生命周期不会至少不会随着线程技术而结束。</li>
<li>ThreadLocal 对象存在，并且 <code>Entry的 key == null &amp;&amp; value != null</code> ，这时就会造成内存泄漏。</li>
</ol>
<ul>
<li>小补充</li>
</ul>
<ol>
<li>强引用、软引用、弱引用、虚引用<pre><code class="text">强引用（StrongReference）：最常见，直接 new Object(); 创建的即为强引用。当内存空间不足，Java虚拟机宁愿抛出 OOM，也不愿意随意回收具有强引用的对象来解决内存不足问题。
软引用（SoftReference）：内存足够，垃圾回收器不会回收软引用对象；内存不足时，垃圾回收器会回收。
弱引用（WeakReference）：垃圾回收器线程，发现就会回收。
虚引用（PhantomReference）：任何时候都有可能被垃圾回收，必须引用队列联合使用。</code></pre>
</li>
<li>内存泄露：<pre><code class="text">内存泄漏（Memory leak）是在计算机科学中，由于疏忽或错误造成程序未能释放已经不再使用的内存。内存泄漏并非指内存在物理上的消失，而是应用程序分配某段内存后，由于设计错误，导致在释放该段内存之前就失去了对该段内存的控制，从而造成了内存的浪费。
—— 维基百科</code></pre>
</li>
</ol>
<img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/SJPSIU.jpg"  div align=center />

<h5 id="构造函数及hash计算"><a href="#构造函数及hash计算" class="headerlink" title="构造函数及hash计算"></a>构造函数及hash计算</h5><pre><code class="java">ThreadLocalMap(ThreadLocal&lt;?&gt; firstKey, Object firstValue) &#123;
    // 初始化Entry数组， 长度为16
    table = new Entry[INITIAL_CAPACITY];
    // 获取key的hashCode，并计算出在数组中的索引，
    // 长度是 2的幂的情况下，取模 a % b == a &amp; (b - 1)
    int i = firstKey.threadLocalHashCode &amp; (INITIAL_CAPACITY - 1);
    table[i] = new Entry(firstKey, firstValue);
    // 设置数组元素数
    size = 1;
    // 设置扩容阈值
    setThreshold(INITIAL_CAPACITY);
&#125;</code></pre>
<p>threadLocalHashCode 是 ThreadLocal 的静态属性，通过 nextHashCode 方法获取。</p>
<pre><code class="java">private final int threadLocalHashCode = nextHashCode();

// 被赋予了接下来的哈希码。 原子更新。 从零开始。
private static AtomicInteger nextHashCode = new AtomicInteger();

private static final int HASH_INCREMENT = 0x61c88647;
private static int nextHashCode() &#123;
    // 返回下一个hash码，通过步长 0x61c88647 累加生成，这块注释说明是最佳哈希值
    return nextHashCode.getAndAdd(HASH_INCREMENT);
&#125;</code></pre>
<ol>
<li>初始化数组，长度16。</li>
<li>计算 key 的 hashCode，对2的幂取模。</li>
<li>设置元素，元素数及扩容阈值。</li>
</ol>
<p>hashCode 通过步长 0x61c88647 累加生成， 并且使用了 AtomicInteger，保证原子性。</p>
<h5 id="set-方法"><a href="#set-方法" class="headerlink" title="set()方法"></a>set()方法</h5><pre><code class="java">
private void set(ThreadLocal&lt;?&gt; key, Object value) &#123;

    Entry[] tab = table;
    int len = tab.length;
    // hashcode取模求数组索引
    int i = key.threadLocalHashCode &amp; (len-1);

    // 获取数组中对应的位置， 重点关注 e = tab[i = nextIndex(i, len)]
    for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) &#123;
        // 获取key
        ThreadLocal&lt;?&gt; k = e.get();
        // key 存在则覆盖
        if (k == key) &#123;
            e.value = value;
            return;
        &#125;
        // key 不存在则赋值
        if (k == null) &#123;
            replaceStaleEntry(key, value, i);
            return;
        &#125;
    &#125;
    // 此时 e == null 直接执创建节点
    tab[i] = new Entry(key, value);
    int sz = ++size;
    // cleanSomeSlots 循环数组 查找全部key==null的Entry
    if (!cleanSomeSlots(i, sz) &amp;&amp; sz &gt;= threshold)
        rehash();
&#125;</code></pre>
<ol>
<li>获取循环 Entry 数组，获取 tab[i] 处的 e， e != null 继续循环<ol>
<li>此时发现 e 的 key 不存在，并且不是 null （hash冲突了。）</li>
<li>那就通过 e = tab[i = nextIndex(i, len)]) 继续获取下一个 i，并获取新的 tab[i] 处的 e。</li>
<li>赋值替换值结束结束并返回。</li>
</ol>
</li>
<li>e == null 结束循环。</li>
</ol>
<pre><code class="java">// 下一个index，如果 i + 1 &lt; len 直接返回下一个位置  
// 如果 i + 1 &gt;= len 则返回 0， 从头开始。
private static int nextIndex(int i, int len) &#123;
    return ((i + 1 &lt; len) ? i + 1 : 0);
&#125;

private static int prevIndex(int i, int len) &#123;
    return ((i - 1 &gt;= 0) ? i - 1 : len - 1);
&#125;
</code></pre>
<ol>
<li>这块利用环形设计，如果长度到达数组长度，则从开头开始继续查找。</li>
<li>int i = key.threadLocalHashCode &amp; (len-1); 求出索引，并不是从0开始的。</li>
</ol>
<pre><code class="java">
/**
 * staleSlot 为当前索引位置， 并且当前索引位置的 k == null
 */
private void replaceStaleEntry(ThreadLocal&lt;?&gt; key, Object value, int staleSlot) &#123;
    Entry[] tab = table;
    int len = tab.length;
    Entry e;

    // 需要清除的 entry 的索引
    int slotToExpunge = staleSlot;

    // 循环获取到上一个 key==null 的节点及其索引，有可能还是自己
    for (int i = prevIndex(staleSlot, len); (e = tab[i]) != null; i = prevIndex(i, len))
        if (e.get() == null)
            slotToExpunge = i;

    // 继续上一层的循环，查找下一个 k == key 的节点索引
    for (int i = nextIndex(staleSlot, len); (e = tab[i]) != null; i = nextIndex(i, len)) &#123;
        ThreadLocal&lt;?&gt; k = e.get();

        if (k == key) &#123;
            // key 相等 则直接赋值
            e.value = value;
            // 并且将 此处的 entry替换为 tab[staleSlot]
            tab[i] = tab[staleSlot];
            tab[staleSlot] = e;

            // 如果发现要清除的 entry和传入的在一个位置上， 则直接赋值
            if (slotToExpunge == staleSlot)
                slotToExpunge = i;

            // 清除掉过期的 expungeStaleEntry(slotToExpunge) 会清除 entry的value，将其设置为null并将其设置为null， 并返回下一个需要清除的entry的索引位置
            // cleanSomeSlots 循环数组 查找全部key==null的Entry
            cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
            return;
        &#125;

        // 如果向后扫描没有找到，并且已经到第初始传入的索引位置处了
        if (k == null &amp;&amp; slotToExpunge == staleSlot)
            slotToExpunge = i;
    &#125;

    // 没找到， 直接将旧值 Entry 设置为 null 并指向新创建的Entry
    tab[staleSlot].value = null;
    tab[staleSlot] = new Entry(key, value);

    // 结束之后发现要清楚的 key的索引 不等于当前传入的索引， 说明还有其他需要清除。
    if (slotToExpunge != staleSlot)
        cleanSomeSlots(expungeStaleEntry(slotToExpunge), len);
&#125;
</code></pre>
<ol>
<li>这里存在三个属性 key， value，以及 staleSlot， staleSlot节点的 Entry != null 但是 k == null。</li>
<li>向前扫描获取到上一个  Entry != null 但是 k == null 的节点及其索引, 赋值给 slotToExpunge， 没有扫描到的话 slotToExpunge 还是等于 staleSlot。</li>
<li>向后扫描 Entry != null 的节点，因为在 set 方法中， 后面还有一段数组没有遍历。<ol>
<li>发现 key 相等的Entry节点了， 直接赋值，然后清除其他 Entry != null 但是 k == null 的节点， 并返回。</li>
<li>没有找到key相等的节点，但是找到了下一个 Entry != null 但是 k == null， 且此时 slotToExpunge 未发生变化，还是指向 staleSlot， 则 i 赋值给 slotToExpunge。</li>
</ol>
</li>
<li>向后扫描没有扫描到，则直接对当前节点（索引值为staleSlot）的节点的value设置为null，并指向新value。</li>
<li>结束之后发现 slotToExpunge 被改变了， 说明还有其他的要清除。</li>
</ol>
<h5 id="getEntry-方法"><a href="#getEntry-方法" class="headerlink" title="getEntry()方法"></a>getEntry()方法</h5><pre><code class="java">
private Entry getEntry(ThreadLocal&lt;?&gt; key) &#123;
    // hashcode取模求数组索引
    int i = key.threadLocalHashCode &amp; (table.length - 1);
    Entry e = table[i];
    if (e != null &amp;&amp; e.get() == key)
        // 存在则返回
        return e;
    else
        // 不存在
        return getEntryAfterMiss(key, i, e);
&#125;

private Entry getEntryAfterMiss(ThreadLocal&lt;?&gt; key, int i, Entry e) &#123;
    Entry[] tab = table;
    int len = tab.length;

    while (e != null) &#123;
        ThreadLocal&lt;?&gt; k = e.get();
        if (k == key)
            return e;
        if (k == null)
            // key 已经 == null 了 清除一下 value
            expungeStaleEntry(i);
        else
            // 继续获取下一个
            i = nextIndex(i, len);
        e = tab[i];
    &#125;
    return null;
&#125;</code></pre>
<ol>
<li>hashcode 取模求数组索引。</li>
<li>索引处获取到 Entry 则直接返回。</li>
<li>获取不到或者获取到的 Entry key 不相等时，有可能是因为 hash 冲突，被放到别的地方， 调用 getEntryAfterMiss 方法。</li>
<li>getEntryAfterMiss 方法中。<ol>
<li>e == null  返回null。</li>
<li>e != null  判断key， key相等返回 Entry， key == null， 那就需要清除这个节点，然后继续按照 <code>nextIndex(i, len)</code> 方法找下一个节点。</li>
</ol>
</li>
</ol>
<h4 id="remove-方法-1"><a href="#remove-方法-1" class="headerlink" title="remove()方法"></a>remove()方法</h4><pre><code class="java">
private void remove(ThreadLocal&lt;?&gt; key) &#123;
    Entry[] tab = table;
    int len = tab.length;
    // hashcode 取模求数组索引
    int i = key.threadLocalHashCode &amp; (len-1);
    // 清除当前节点的value
    for (Entry e = tab[i]; e != null; e = tab[i = nextIndex(i, len)]) &#123;
        if (e.get() == key) &#123;
            // 清楚对象引用
            e.clear();
            // value 指向 null
            expungeStaleEntry(i);
            return;
        &#125;
    &#125;
&#125;
public void clear() &#123;
    this.referent = null;
&#125;</code></pre>
<ol>
<li>hashcode 取模求数组索引。</li>
<li>循环查找数组，将当前 key 的 Entry 的引用，将 value 设置为 null， 后面会被垃圾回收掉。</li>
</ol>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h3><h4 id="为什么可以线程私有？"><a href="#为什么可以线程私有？" class="headerlink" title="为什么可以线程私有？"></a>为什么可以线程私有？</h4><p>ThreadLocal 的 get()、set()、remove()方法中都有 <code>Thread t = Thread.currentThread();</code> 操作的其实是本线程，获取本线程的ThreadLocalMap。</p>
<p>每个线程都有自己的 ThreadLocal，并且是将 value 存放在一个以 ThreadLocal 为 key 的 ThreadLocalMap 中的。所以线程间隔离。</p>
<h4 id="为什么建议声明为静态？"><a href="#为什么建议声明为静态？" class="headerlink" title="为什么建议声明为静态？"></a>为什么建议声明为静态？</h4><p>Java开发手册已经给出说明，还有就是，如果 ThreadLocal 设置为非静态，那就是某个线程的实例类，这样的话就会失去了线程共享的本质属性。</p>
<h4 id="为什么强制必须时候后remove-？"><a href="#为什么强制必须时候后remove-？" class="headerlink" title="为什么强制必须时候后remove()？"></a>为什么强制必须时候后remove()？</h4><p>这块可以和内存泄露一块说明， 通过上面的 <code>ThreadLocalMap</code> 处关于弱引用的讲解已经说明会产生内存泄露。至于如何解决也给出了答案：</p>
<p>1.<code>set()</code> 时清除 Entry != null &amp;&amp; key == null 的节点， 将其 value 设置为 null。<br>2.<code>getEntry()</code> 时清除<code>当前 key 到 nextIndex(i, len)==null 之间的</code> Entry != null &amp;&amp; key == null 的节点， 将其 value 设置为 null。<br>3.<code>remove()</code> 时清除<code>指定key</code>的 Entry != null &amp;&amp; key == null 的节点， 将其 value 设置为 null。</p>
<p>之所以使用remove()，还是为了解决内存泄露的问题。</p>
<h4 id="Last"><a href="#Last" class="headerlink" title="Last"></a>Last</h4><ol>
<li>使用时注意声明为 <code>private static final</code>。</li>
<li>使用后要 <code>remove()</code>。</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">liuzhihang</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://liuzhihang.com/2020/06/21/source-code-threadlocal.html">https://liuzhihang.com/2020/06/21/source-code-threadlocal.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://liuzhihang.com" target="_blank">程序员小航</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%BA%90%E7%A0%81%E7%AC%94%E8%AE%B0/">源码笔记</a><a class="post-meta__tags" href="/tags/JDK/">JDK</a></div><div class="post_share"><div class="social-share" data-image="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/threadlocal.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2020/06/28/source-code-longadder.html"><img class="prev-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/longadder-article.jpeg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">【JDK源码笔记】- JDK 8 新增的 LongAdder，得过来看一下！</div></div></a></div><div class="next-post pull-right"><a href="/2020/06/12/source-code-cas.html"><img class="next-cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" onerror="onerror=null;src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/2020/07/12/source-code-aqs.html" title="【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/aqs-uhgQnu.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-07-12</div><div class="title">【JDK源码笔记】- 别走！这里有个笔记：图文讲解 AQS ，一起看看 AQS 的源码……(图文较长)</div></div></a></div><div><a href="/2020/09/27/source-code-arrayblockingqueue.html" title="【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ArrayBlockingQueue-cover-ESuNmo.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-09-27</div><div class="title">【JDK源码笔记】- 基于数组的有界阻塞队列 —— ArrayBlockingQueue</div></div></a></div><div><a href="/2020/06/12/source-code-cas.html" title="【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......"><img class="cover" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/cas.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-06-12</div><div class="title">【JDK源码笔记】- 从JUC源码看CAS，我做了个笔记 ......</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div id="gitalk-container"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/404/avatar.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">liuzhihang</div><div class="author-info__description">学，然后知不足；教，然后知困。</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">145</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">55</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">31</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liuzhihang"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liuzhihang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="http://mail.qq.com/cgi-bin/qm_share?t=qm_mailme&amp;email=Vjo-Iyw_Pz43ODElFicneDU5Ow" target="_blank" title="Email"><i class="fas fa-envelope-open"></i></a><a class="social-icon" href="https://weibo.com/onlyhang" target="_blank" title="Weibo"><i class="fab fa-weibo"></i></a><a class="social-icon" href="https://twitter.com/liuzhihangs" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a><a class="social-icon" href="https://www.infoq.cn/u/liuzhihang/publish" target="_blank" title="InfoQ"><i class="iconfont iconweibiaoti-1"></i></a><a class="social-icon" href="https://juejin.im/user/1987506650493117" target="_blank" title="掘金"><i class="iconfont iconjuejin-1"></i></a><a class="social-icon" href="https://blog.csdn.net/qq_36535538" target="_blank" title="CSDN"><i class="iconfont iconcsdn"></i></a><a class="social-icon" href="https://www.zhihu.com/people/liuzhihang" target="_blank" title="知乎"><i class="iconfont iconzhihu1"></i></a><a class="social-icon" href="https://leetcode-cn.com/u/liuzhihang" target="_blank" title="LeetCode"><i class="iconfont iconleetcode"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">🧑‍💻感谢访问本站，若喜欢请收藏 ^_^ <br> <br> <img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/wechat.jpg"> <br> 个人公众号:『 程序员小航 』</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%8B%E7%BB%8D"><span class="toc-text">介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8"><span class="toc-text">使用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%A6%82%E4%B8%8B%EF%BC%9A"><span class="toc-text">代码如下：</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8A%9B%E5%87%BA%E9%97%AE%E9%A2%98"><span class="toc-text">抛出问题</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90"><span class="toc-text">源码分析</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#Thread"><span class="toc-text">Thread</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ThreadLocal"><span class="toc-text">ThreadLocal</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#set-T-value-%E6%96%B9%E6%B3%95"><span class="toc-text">set(T value)方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#get-%E6%96%B9%E6%B3%95"><span class="toc-text">get()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#remove-%E6%96%B9%E6%B3%95"><span class="toc-text">remove()方法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#ThreadLocalMap"><span class="toc-text">ThreadLocalMap</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%8F%8Ahash%E8%AE%A1%E7%AE%97"><span class="toc-text">构造函数及hash计算</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#set-%E6%96%B9%E6%B3%95"><span class="toc-text">set()方法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#getEntry-%E6%96%B9%E6%B3%95"><span class="toc-text">getEntry()方法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#remove-%E6%96%B9%E6%B3%95-1"><span class="toc-text">remove()方法</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%BB%E7%BB%93"><span class="toc-text">总结</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%8F%AF%E4%BB%A5%E7%BA%BF%E7%A8%8B%E7%A7%81%E6%9C%89%EF%BC%9F"><span class="toc-text">为什么可以线程私有？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%BB%BA%E8%AE%AE%E5%A3%B0%E6%98%8E%E4%B8%BA%E9%9D%99%E6%80%81%EF%BC%9F"><span class="toc-text">为什么建议声明为静态？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E5%BC%BA%E5%88%B6%E5%BF%85%E9%A1%BB%E6%97%B6%E5%80%99%E5%90%8Eremove-%EF%BC%9F"><span class="toc-text">为什么强制必须时候后remove()？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#Last"><span class="toc-text">Last</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/uztio4-T5n5Wm.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="使用 SpringBoot 转换器将前端参数转换为枚举"/></a><div class="content"><a class="title" href="/2021/09/04/the_converter_converts_front_end_parameters_to_enumerations.html" title="使用 SpringBoot 转换器将前端参数转换为枚举">使用 SpringBoot 转换器将前端参数转换为枚举</a><time datetime="2021-09-03T23:00:00.000Z" title="发表于 2021-09-04 07:00:00">2021-09-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/ze1d2z-wXDWp0.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="MyBatis-Plus 中 Mapper 重载踩坑指南"/></a><div class="content"><a class="title" href="/2021/08/22/guide_to_mapper_overloading_crater_in_mybatis_plus.html" title="MyBatis-Plus 中 Mapper 重载踩坑指南">MyBatis-Plus 中 Mapper 重载踩坑指南</a><time datetime="2021-08-21T23:00:00.000Z" title="发表于 2021-08-22 07:00:00">2021-08-22</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/MODJ8j-9ObHeB.jpg" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="并发场景加锁优化小技巧"/></a><div class="content"><a class="title" href="/2021/07/25/tips_for_locking_and_optimizing_concurrent_scenes.html" title="并发场景加锁优化小技巧">并发场景加锁优化小技巧</a><time datetime="2021-07-24T23:00:00.000Z" title="发表于 2021-07-25 07:00:00">2021-07-25</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁"/></a><div class="content"><a class="title" href="/2021/07/16/curator-5.html" title="ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁">ZooKeeper 分布式锁 Curator 源码 05：分布式读写锁和联锁</a><time datetime="2021-07-16T13:30:30.000Z" title="发表于 2021-07-16 21:30:30">2021-07-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"><img src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/article/EO0tci-8Ju4bN.png" onerror="this.onerror=null;this.src='https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/feature/92776_n5aac6.jpg'" alt="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁"/></a><div class="content"><a class="title" href="/2021/07/15/curator-4.html" title="ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁">ZooKeeper 分布式锁 Curator 源码 04：分布式信号量和互斥锁</a><time datetime="2021-07-15T13:30:30.000Z" title="发表于 2021-07-15 21:30:30">2021-07-15</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2017 - 2021 By liuzhihang</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><img class="icp-icon" src= "https://cdn.jsdelivr.net/gh/liuzhihang/oss/pic/loading.gif" data-lazy-src="/resources/image/icp.png"><span>备案号：京ICP备20000888号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script><script>function addGitalkSource () {
  const ele = document.createElement('link')
  ele.rel = 'stylesheet'
  ele.href= 'https://cdn.jsdelivr.net/npm/gitalk/dist/gitalk.min.css'
  document.getElementsByTagName('head')[0].appendChild(ele)
}

function loadGitalk () {
  function initGitalk () {
    var gitalk = new Gitalk(Object.assign({
      clientID: 'e48f300349e2ac2d03bd',
      clientSecret: '001c669e6269dfd9d7d9fef029cc71fd00ea69e3',
      repo: 'comments',
      owner: 'liuzhihang',
      admin: ['liuzhihang'],
      id: 'baa9d9fa32d1b164e09325a5eb3b6eef',
      language: 'en',
      perPage: 10,
      distractionFreeMode: false,
      pagerDirection: 'last',
      createIssueManually: false,
      updateCountCallback: commentCount
    },null))

    gitalk.render('gitalk-container')
  }

  if (typeof Gitalk === 'function') initGitalk()
  else {
    addGitalkSource()
    getScript('https://cdn.jsdelivr.net/npm/gitalk@latest/dist/gitalk.min.js').then(initGitalk)
  }
}

function commentCount(n){
  let isCommentCount = document.querySelector('#post-meta .gitalk-comment-count')
  if (isCommentCount) {
    isCommentCount.innerHTML= n
  }
}

if ('Gitalk' === 'Gitalk' || !false) {
  if (false) btf.loadComment(document.getElementById('gitalk-container'), loadGitalk)
  else loadGitalk()
} else {
  function loadOtherComment () {
    loadGitalk()
  }
}</script></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>